<script setup lang="ts">
import { useAuthSession } from '../../../composables/useAuthSession'

const route = useRoute()
const id = computed(() => route.params.id as string)
const { user, refresh: refreshAuth } = useAuthSession()
const { fetchData } = useClientApi()
const toast = useToast()

const state = reactive({
  title: '',
  slug: '',
  excerpt: '',
  bodyMarkdown: '',
  visibility: 'private',
  shareToken: '' as string | null,
})
const loading = ref(true)
const saving = ref(false)

const publicPostHref = computed(() => {
  const ps = user.value?.publicSlug
  if (state.visibility !== 'public' || !ps || !state.slug) {
    return ''
  }
  return `/@${ps}/posts/${encodeURIComponent(state.slug)}`
})

async function load(options?: { silent?: boolean }) {
  const silent = options?.silent === true
  if (!silent) {
    loading.value = true
  }
  try {
    const { post: p } = await fetchData<{ post: typeof state }>(`/api/me/posts/${id.value}`)
    Object.assign(state, {
      title: p.title,
      slug: p.slug,
      excerpt: p.excerpt,
      bodyMarkdown: p.bodyMarkdown,
      visibility: p.visibility,
      shareToken: p.shareToken ?? null,
    })
  } finally {
    if (!silent) {
      loading.value = false
    }
  }
}

onMounted(() => {
  void refreshAuth(true)
  void load()
})

watch(id, () => {
  void load()
})

usePageTitle(() => {
  const t = state.title.trim()
  return t ? [t, '编辑'] : ['编辑文章']
})

async function save() {
  saving.value = true
  try {
    await fetchData(`/api/me/posts/${id.value}`, {
      method: 'PUT',
      body: {
        title: state.title,
        slug: state.slug,
        excerpt: state.excerpt,
        bodyMarkdown: state.bodyMarkdown,
        visibility: state.visibility,
      },
    })
    await load({ silent: true })
    toast.add({ title: '文章已保存', color: 'success' })
  } finally {
    saving.value = false
  }
}

async function remove() {
  await fetchData(`/api/me/posts/${id.value}`, { method: 'DELETE' })
  toast.add({ title: '文章已删除', color: 'success' })
  await navigateTo('/me/posts')
}

const shareUrl = computed(() => {
  const slug = user.value?.publicSlug
  if (state.visibility !== 'unlisted' || !state.shareToken || !slug) {
    return ''
  }
  if (import.meta.client) {
    return `${window.location.origin}/p/${slug}/t/${state.shareToken}`
  }
  return ''
})
</script>

<template>
  <UContainer class="py-8 max-w-6xl space-y-6">
    <div class="flex flex-wrap items-center justify-between gap-3">
      <h1 class="text-2xl font-semibold tracking-tight">
        编辑文章
      </h1>
      <div class="flex flex-wrap items-center gap-2">
        <UButton
          v-if="publicPostHref"
          :to="publicPostHref"
          variant="soft"
          color="neutral"
          size="sm"
        >
          详情
        </UButton>
        <UButton to="/me/posts" variant="ghost" color="neutral" size="sm">
          返回列表
        </UButton>
      </div>
    </div>

    <div v-if="loading" class="text-muted">
      加载中…
    </div>

    <template v-else>
      <UForm :state="state" class="space-y-6" @submit.prevent="save">
        <UCard :ui="{ body: 'p-4 sm:p-6' }">
          <PostBodyMarkdownEditor v-model="state.bodyMarkdown" />
          <UFormField label="正文" name="bodyMarkdown" required class="sr-only" />
        </UCard>

        <UCard :ui="{ body: 'p-4 sm:p-6 space-y-4' }">
          <UCollapsible :unmount-on-hide="false">
            <UButton
              type="button"
              color="neutral"
              variant="subtle"
              block
              class="justify-between font-medium"
              label="文章设置"
              trailing
              trailing-icon="i-lucide-chevron-down"
            />
            <template #content>
              <div class="pt-4 space-y-4 border-t border-default mt-4">
                <UAlert
                  v-if="shareUrl"
                  title="仅链接分享"
                  :description="shareUrl"
                />
                <UFormField label="标题" name="title" required>
                  <UInput v-model="state.title" />
                </UFormField>
                <UFormField label="slug" name="slug" required>
                  <UInput v-model="state.slug" />
                </UFormField>
                <UFormField label="摘要" name="excerpt" required>
                  <UInput v-model="state.excerpt" />
                </UFormField>
                <UFormField label="可见性" name="visibility">
                  <USelect
                    v-model="state.visibility"
                    :items="[
                      { label: '私密', value: 'private' },
                      { label: '公开', value: 'public' },
                      { label: '仅链接', value: 'unlisted' },
                    ]"
                  />
                </UFormField>
              </div>
            </template>
          </UCollapsible>
        </UCard>

        <div class="flex flex-wrap gap-2">
          <UButton type="submit" :loading="saving">
            保存
          </UButton>
          <UButton color="error" variant="soft" type="button" @click="remove">
            删除
          </UButton>
        </div>
      </UForm>
    </template>
  </UContainer>
</template>
